package com.cjst.controller.base;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjst.config.CreateWord;
import com.cjst.config.DocUtil;
import com.cjst.config.ZXingCode;
import com.cjst.controller.base.BaseController;
import com.cjst.pojo.base.QRCode;
import com.cjst.pojo.sys.SysUser;
import com.cjst.sdp.util.MapUtils;
import com.cjst.service.base.OrderIdService;
import com.cjst.service.base.QRCodeService;
import com.cjst.service.sys.SysDictService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.CloneClass;
import com.cjst.util.QrCodeUtil;
import com.cjst.util.UserPrincipalUtil;
import com.cjst.util.code.PageUtil;
import com.cjst.util.common.CommonConstant;
import com.cjst.util.common.DateUtil;
import com.cjst.util.json.ResultObj;
import com.google.zxing.WriterException;
import com.lowagie.text.Image;
/**
 * 二维码controller
 * @author 76558
 *
 */
@Controller
@RequestMapping("/base/qrcode")
public class QRCodeController extends BaseController{

	@Autowired
	private SysDictService dictService;
	
	@Autowired
	private OrderIdService orderIdService;
	
	@Autowired
	private QRCodeService qrcodeService;
	
	
	@RequestMapping(value = "", method = RequestMethod.GET)
    //@RequiresPermissions("t_qr_code")
    public String toList(Model model) {
		List<Map<String, String>> codes = dictService.getDicts("code_type");
		if(codes!=null&&codes.size()>0) {
			model.addAttribute("codes", codes);
		}
        return "base/qrcode/list";
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/toAdd", method = RequestMethod.GET)
    @RequiresPermissions("qrcode_add")
    public String toAdd(Model model) {
    	List<Map<String, String>> codes = dictService.getDicts("code_type");
		if(codes!=null&&codes.size()>0) {
			model.addAttribute("codes", codes);
		} 
        return "base/qrcode/add";
    }
    
    @RequestMapping(value = "/toView/{id}", method = RequestMethod.GET)
    @RequiresPermissions("qrcode_view")
    public String toView(Model model,@PathVariable String id) {
    	if(StringUtils.isNotEmpty(id)) {
    		QRCode code = qrcodeService.get(id);
    		if(code!=null) {
    			String fileUrl = code.getCodeImg();
    			if(StringUtils.isEmpty(fileUrl)) {
    				//文件url不存在，则重新创建二维码
    	        	fileUrl = createQRCode(code.getCodeNum());
    	        	//并且更新二维码数据
    	        	code.setCodeImg(fileUrl);
    	        	qrcodeService.updateLocal(code);
    			}
    			String serverPath = imgLocation;
    	    	//获取系统环境
    			log.info("====================System.getenv():"+System.getenv().get("OS"));
    	    	/*if(System.getenv().get("OS").contains("Windows")) {
    	    		serverPath = winFileUploadPath;
    	    	}else {
    	    		serverPath = linuxFileUploadPath;
    	    	}*/
    	    	 //检查二维码图片是否存在
    	        File dir = new File(serverPath + fileUrl);
    	        if (!dir.exists()) {
    	            //文件不存在，则重新创建二维码
    	        	fileUrl = createQRCode(code.getCodeNum());
    	        	//并且更新二维码数据
    	        	code.setCodeImg(fileUrl);
    	        	
    	        	qrcodeService.updateLocal(code);
    	        }
    			model.addAttribute("url", fileServerPath+fileUrl);
    		}
    		model.addAttribute("codeNum", code.getCodeNum());
    	}
    	
        return "base/qrcode/code_view";
    }
      
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("qrcode")
    public Object listQRCodes(QRCode code) {
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        
    	Map<String, Object> authMap = UserPrincipalUtil.getUserPrincipals(sysUser);
    	if("-1".equals(authMap.get("auth"))) {
    		return null;
    	}
    	
    	WherePrams prams = Method.where("isDel", C.EQ, "0");
    	//根据查询条件过滤结果
    	if(code != null) {
    		String codeNum = code.getCodeNum();
    		String codeType = code.getCodeType();
    		String status = code.getStatus();
    		if(StringUtils.isNotEmpty(codeNum)) {
    			prams.and("codeNum", C.LIKE, codeNum);
    		}
    		if(StringUtils.isNotEmpty(codeType)) {
    			prams.and("codeType", C.EQ, codeType);
    		}
    		if(StringUtils.isNotEmpty(status)) {
    			prams.and("status", C.EQ, status);
    		}
    		
    	}
    	//根据权限过滤结果
    	if("2".equals(authMap.get("auth"))) {
			prams.andIn("createBy", C.IN, (List<String>)authMap.get("users"));
		}
    	prams.orderBy(" code_num desc");
    	PageUtil<QRCode> pageUtil = qrcodeService.listPageCount(prams);
    	
    	List<QRCode> codes = pageUtil.getData();
        List<Map<String, Object>> maps = new ArrayList<>();
        for (QRCode qrCode : codes) {
            Map<String, Object> codeMap = MapUtils.transBean2Map(qrCode);
            String codeTypeVal = dictService.getDictVal("code_type", qrCode.getCodeType());
            if(StringUtils.isNotEmpty(codeTypeVal)) {
            	codeMap.put("codeTypeVal", codeTypeVal);
            }
            
            String codeNum= qrCode.getCodeNum();
            WherePrams insurPrams = Method.where("isDel", C.EQ, "0");
            insurPrams.and("qrcodeNo", C.EQ, codeNum);
            
            maps.add(codeMap);
        }

        PageUtil<Map<String, Object>> pages = new PageUtil<>();

        CloneClass.getClone(pageUtil, pages);
        pages.setData(maps);
        return this.packForBT(pages);
    }
    
     /**
      * 根据传入的数量和二维码类型，批量生成二维码
      * @param codeType
      * @param num
      * @return
      */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    @RequiresPermissions("qrcode_add")
    public Object add(String codeType,Integer num) {
     	
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if (null == sysUser) {
        	return new ResultObj(0,"用户未登陆，无法操作",null);
        }
    	
    	if(StringUtils.isEmpty(codeType)) {
     		return new ResultObj(0,"二维码类型不能为空",null);
     	}
     	if(num==null||num<=0) {
     		return new ResultObj(0,"需要创建的二维码数量不能小于0",null);
     	}
     	//根据codeType从数据字典中获取生成订单的前缀
     	
     	
     	//检查数量限制，一次生成不能超过50个
     	if(num>50) {
     		return new ResultObj(0,"二维码一次创建的数量不能超过50个",null);
     	}
     	for (int i = 0; i < num; i++) {
			QRCode qrCode = new QRCode();
			//逐条生成二维码编号
			String codeNum = orderIdService.getOrderIdByProc(codeType);
			//根据二维码编号生成二维码，并返回图片路径  todo
			
			qrCode.setCodeNum(codeNum);
			qrCode.setStatus("1");
			qrCode.setIsDel("0");
			qrCode.setCodeType(codeType);
			qrCode.setCreateTime(DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_WITHSECOND_FORMAT));
			qrCode.setCreateBy(sysUser.getId()); //设置创建人
			
			//调用生成二维码并返回路径的方法
			String fileUrl = createQRCode(codeNum);
			
			if(StringUtils.isEmpty(fileUrl)) {
				return new ResultObj(0,"生成二维码异常",null);
			}
			qrCode.setCodeImg(fileUrl);
			
			qrcodeService.addLocalByid(qrCode);
     		
		}
        return new ResultObj(1,"批量生成二维码成功",null);
    }
    
    /**
     * 批量删除二维码
     * @param ids
     * @return
     */
    @RequestMapping(value="/del",method = RequestMethod.POST)
    @RequiresPermissions("qrcode_del")
    @ResponseBody
    public Object delCodes(String ids) {
    	if(StringUtils.isEmpty(ids)) {
    		return new ResultObj(0, "参数传递为空，删除二维码失败", null);
    	}
    	//获取二维码Id列表
    	List<String> codeIds = Arrays.asList(ids.split(","));
    	
    	List<String> noAllowCodeIds = new ArrayList<>();
    	
    	for (String codeId : codeIds) {
			
    		QRCode code = qrcodeService.get(codeId);
    		if(code!=null){
    			//如果状态不为已创建，则无法删除
    			if(!"1".equals(code.getStatus())) {
    				noAllowCodeIds.add(code.getCodeNum());
    			}
    		}
		}
    	if(noAllowCodeIds.size()>0) {
    		String codeNums = "";
    		for (String codeNum : noAllowCodeIds) {
				codeNums+="["+codeNum+"],";
			}
    		codeNums = codeNums.substring(0, codeNums.length()-1);
    		return new ResultObj(0, "二维码编号为"+codeNums+"的二维码状态不为已创建，二维码无法删除", null);
    	}
    	//开始删除逻辑
    	for (String codeId : codeIds) {
			
    		QRCode code = new QRCode();
    		code.setId(codeId);
    		code.setIsDel("1");
    		qrcodeService.updateLocal(code);
		}
    	return new ResultObj(1, "删除成功", null);
    }
    
    /**
     * 批量打印二维码
     * @param ids
     * @return
     */
    @RequestMapping(value="/print",method = RequestMethod.POST)
    @RequiresPermissions("qrcode_print")
    @ResponseBody
    public Object printCodes(String ids) {
    	if(StringUtils.isEmpty(ids)) {
    		return new ResultObj(0, "参数传递为空，打印二维码失败", null);
    	}
    	//获取二维码Id列表
    	List<String> codeIds = Arrays.asList(ids.split(","));
    	
    	List<String> noAllowCodeIds = new ArrayList<>();
    	
    	for (String codeId : codeIds) {
			
    		QRCode code = qrcodeService.get(codeId);
    		if(code!=null){
    			//todo 需要确认打印之后的时候还能打印
    			
    			//如果状态不为已创建，则无法打印
    			if("3".equals(code.getStatus())) {
    				noAllowCodeIds.add(code.getCodeNum());
    			}
    		}
		}
    	if(noAllowCodeIds.size()>0) {
    		String codeNums = "";
    		for (String codeNum : noAllowCodeIds) {
				codeNums+="["+codeNum+"],";
			}
    		codeNums = codeNums.substring(0, codeNums.length()-1);
    		return new ResultObj(0, "二维码编号为"+codeNums+"的二维码已使用，无法打印二维码", null);
    	}
    	//开始修改二维码状态
    	for (String codeId : codeIds) {
			
    		QRCode code = new QRCode();
    		code.setId(codeId);
    		code.setStatus("2");
    		code.setPrintTime(DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_WITHSECOND_FORMAT));
    		qrcodeService.updateLocal(code);
		}
    	
    	//todo  具体的打印逻辑
    	return new ResultObj(1, "已打印", null);
    }
    
    /**
     * 打印选中
     * @param ids
     * @param model
     * @return
     */
    @RequestMapping(value="/toPrint",method = RequestMethod.GET)
    public String printAllCodes(String ids, Model model) {
    	if(StringUtils.isNotEmpty(ids)) {
    		model.addAttribute("ids", ids);
    		//获取二维码Id列表
        	List<String> codeIds = Arrays.asList(ids.split(","));
        	WherePrams prams = Method.where("isDel", C.EQ, "0");
        	prams.andIn("id", C.IN,codeIds);
        	
        	List<QRCode> codes = qrcodeService.list(prams);
        	if(codes!=null) {
        		for (QRCode qrCode : codes) {
        			String fileUrl = qrCode.getCodeImg();
        			if(StringUtils.isEmpty(fileUrl)) {
        				//文件url不存在，则重新创建二维码
        	        	fileUrl = createQRCode(qrCode.getCodeNum());
        	        	//并且更新二维码数据
        	        	qrCode.setCodeImg(fileUrl);
        	        	qrcodeService.updateLocal(qrCode);
        			}
        			String serverPath = imgLocation;
        	    
        	    	 //检查二维码图片是否存在
        	        File dir = new File(serverPath + fileUrl);
        	        if (!dir.exists()) {
        	            //文件不存在，则重新创建二维码
        	        	fileUrl = createQRCode(qrCode.getCodeNum());
        	        	//并且更新二维码数据
        	        	qrCode.setCodeImg(fileUrl);
        	        	
        	        	qrcodeService.updateLocal(qrCode);
        	        }
        	        
        	        qrCode.setCodeImg(fileServerPath+fileUrl);
				}
        		model.addAttribute("codes", codes);
        	}
    	}
    	return "base/qrcode/print";
    }
    
    
    
    
    
    @Value("${img.location}")
    private String imgLocation;
    
    @Value("${img.location-linux}")
    private String linuxFileUploadPath;
    
    @Value("${img.location-window}")
    private String winFileUploadPath;

    @Value("${img.server-locations}")
    private String fileServerPath;
    @Value("${file.pathQr}")
    private String filePathQr;
    
    
    @Value("${QRCode.size}")
    private int qrcodeSize;
    
    /**
     * 创建二维码并返回二维码的访问路径
     * @param codeNum
     * @return
     */
    private String createQRCode(String codeNum) {
    	
    	String date = DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_SHORT_SIMPLE_FORMAT);
    	String year = date.substring(0,4);
    	String month = date.substring(4, 6);
    	String day = date.substring(6, 8);
    	
    	String serverPath = imgLocation;
    	//获取系统环境
    	/*if(System.getenv().get("OS").contains("Windows")) {
    		serverPath = winFileUploadPath;
    	}else {
    		serverPath = linuxFileUploadPath;
    	}*/
    	
    	String uploadDir = "/qrcode/"+year+"/"+month+"/"+day;
    	
    	 //检查目录是否存在
        File dir = new File(serverPath + uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    	//随机名称
        String randomFileName = UUID.randomUUID().toString();
        //文件存在服务器上的路径
        String fileUrl = uploadDir + "/" + randomFileName + ".jpg";
        
        //String linkTo = filePathQr+"base/qrcode/scanCode?code="+codeNum;
        String linkTo=codeNum;
        boolean flag = false;
        try {
			flag =  QrCodeUtil.createQrCode(new FileOutputStream(new File(serverPath+fileUrl)), linkTo, 900, "JPEG");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(flag) {
        	return fileUrl;
        }else {
        	return "";
        }	
    }
    
    @RequestMapping(value="/download",method = RequestMethod.GET)
    @ResponseBody
    public void download(HttpServletResponse response, HttpServletRequest request) throws Exception{
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	List<Image> imageList=new ArrayList<Image>();
    	String date = DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_SHORT_SIMPLE_FORMAT);
    	String year = date.substring(0,4);
    	String month = date.substring(4, 6);
    	String day = date.substring(6, 8);
    	String uploadDir = "/qrcode/"+year+"/"+month+"/"+day;
    	
   	 	//检查目录是否存在
        File dir = new File(imgLocation + uploadDir);
        if (!dir.exists()) {
           dir.mkdirs();
        }
        //文件存在服务器上的路径
		//逐条生成二维码编号
    	for(int i=0;i<14;i++){
    		QRCode qrCode = new QRCode();
    		String codeNum = orderIdService.getOrderIdByProc("PT");
    		String imgs=System.currentTimeMillis()+".png";
    		String fileUrl=uploadDir+"/"+imgs;
    		String url=imgLocation+"/"+imgs;
    		ZXingCode.getQRCode(codeNum, "神工科技",url);
    		Image jpeg = Image.getInstance(url);
    		imageList.add(jpeg);
    		qrCode.setCodeNum(codeNum);
			qrCode.setStatus("2");
			qrCode.setIsDel("0");
			qrCode.setCodeType("PT");
			qrCode.setCreateTime(DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_WITHSECOND_FORMAT));
			qrCode.setCreateBy(sysUser.getId()); //设置创建人
			qrCode.setCodeImg(fileUrl);
			qrcodeService.addLocalByid(qrCode);
    	}
    	CreateWord.createDocContext(imageList, request, response,imgLocation);
       /* Map<String, Object> root=new HashMap<String,Object>();
        try {
        	String zyfbPath ="E://image/1563852456523076362.jpg";
            root.put("s13", DocUtil.getImageBase(zyfbPath));
        	new DocUtil().wordDown(response, request, root,"dy.doc");
        }catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }*/
    }
    @RequestMapping(value="/download2",method = RequestMethod.GET)
    @ResponseBody
    public void download2(HttpServletResponse response, HttpServletRequest request) throws Exception{
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	List<Image> imageList=new ArrayList<Image>();
    	String date = DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_SHORT_SIMPLE_FORMAT);
    	String year = date.substring(0,4);
    	String month = date.substring(4, 6);
    	String day = date.substring(6, 8);
    	String uploadDir = "/qrcode/"+year+"/"+month+"/"+day;
    	
   	 	//检查目录是否存在
        File dir = new File(imgLocation + uploadDir);
        if (!dir.exists()) {
           dir.mkdirs();
        }
        //文件存在服务器上的路径
		//逐条生成二维码编号
    	for(int i=0;i<20;i++){
    		QRCode qrCode = new QRCode();
    		String codeNum = orderIdService.getOrderIdByProc("PT");
    		String imgs=System.currentTimeMillis()+".png";
    		String fileUrl=uploadDir+"/"+imgs;
    		String url=imgLocation+"/"+imgs;
    		ZXingCode.getQRCode(codeNum, "神工科技",url);
    		Image jpeg = Image.getInstance(url);
    		imageList.add(jpeg);
    		qrCode.setCodeNum(codeNum);
			qrCode.setStatus("2");
			qrCode.setIsDel("0");
			qrCode.setCodeType("PT");
			qrCode.setCreateTime(DateUtil.dateFormatToString(new Date(), CommonConstant.DATE_WITHSECOND_FORMAT));
			qrCode.setCreateBy(sysUser.getId()); //设置创建人
			qrCode.setCodeImg(fileUrl);
			qrcodeService.addLocalByid(qrCode);
    	}
    	CreateWord.createDocContext2(imageList, request, response,imgLocation);
    }  
     
}





